package com.xm.servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.wxm.servlet.BaseServlet;
import com.xm.uti.Result;

/**
 * 图片上传方法
 * Servlet implementation class ImgServlet
 */
@WebServlet("/admin/ImgServletAdmin")
public class ImgServletAdmin extends BaseServlet {
	/**
	 * 图片上传 localhost:8080/upload demo/ImgServletAdmin?method=uploadImg
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	public void uploadImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取一个输出对象
		PrintWriter out = resp.getWriter();
		// 1、实例化一个上传对象
		SmartUpload smart = new SmartUpload();
		// 2、设置字符集
		smart.setCharset("utf-8");
		// 3、初始化
		smart.initialize(getServletConfig(), req, resp);

		try {
			// 4.上传文件
			smart.upload();
			// 5.保存文件到指定位置(save只提供路径，使用原文件名上传文件)
			smart.save("/images");
			// 获取文件名
			String filename = smart.getFiles().getFile(0).getFileName();
			// 将数据返回
			out.print(Result.toClient(0, "新图片上传成功", filename));
		} catch (SmartUploadException e) {
			// TODO: handle exception
			e.printStackTrace();
			//数据返回
			out.print(Result.toClient(1, "新图片上传失败"));
		}
		out.flush();
		out.close();
	}

}
